let shopcartListData;
//当页面加载的时候调用
window.onload=function(){
    if(sessionStorage.getItem("username")!=null) {
        document.getElementById("toLogin").innerHTML = "个人中心";
        document.getElementById("toLogin").style.color="red";
        document.getElementById("shopNum").style.color = "blue";
        if ($("#toLogin").val() != "登录") {
            $("#toLogin").click(function () {
                location.href = "meCenter.html";
            });
            document.getElementById("register").innerHTML = "退出";
            document.getElementById("register").style.color = "red";
            $("#register").click(function () {
                sessionStorage.clear();
                location.href = "index.html";
            })
        }
    }else
    {
        document.getElementById("toLogin").innerHTML = "登录";
    }
    $.ajax({
        url:"cart/seeCart",
        type:"get",
        datatype:"json",
        data:{
            "userid":sessionStorage.getItem("userid"),
        },
        success:function (res) {
            console.log(res);
            if(res.code==500){
                alert("你还没有登录，请先去登录");
                window.location.href="login.html"
            }
            else{
                let count=0;
                for(let item of res.data)
                    count+=1;
                document.getElementById("shopNum").innerHTML=count;
                document.getElementById("shopNum").style.color="blue";
                //调用渲染方法显示购物车信息
                renderCartList(res.data);
                shopcartListData=res.data;
                //调用计算总价格的方法
                getTotalPrice();
            }
        }
    })
}
function query() {
    $.ajax({
        url:"cart/seeCart",
        type:"get",
        datatype:"json",
        data:{
            "userid":sessionStorage.getItem("userid"),
        },
        success:function (res) {
                shopcartListData=res.data;
                //调用计算总价格的方法
                totalPrice();
            }
    })
}
//渲染购物车列表信息
function renderCartList(shopcartListData){
    //定义数组的头部信息
    let tableStart=`<table class='shoptable'>`;
    let tableHeader=`
        <thead>
            <tr>
                <th>
                    <input type='checkbox' onclick="checkAll()" id="selectAll">
                    <span>全选</span>
                </th>
                <th>图片</th>
                <th>商品名称</th>
                <th>单价</th>
                <th>数量</th>
                <th>小计</th>
                <th>操作</th>
            </tr>
        </thead>
    `
    let tablebody='';
    for(let item of shopcartListData){
        let tableBodyTr=`
            <tr>
                <td><input type='checkbox' onclick="selectGood(${item.id})" class="checkbox" id="${item.id}"/></td>
                <td>
                   <div class="shopimg">
                       <img src='${item.goods.image}'>
                   </div>
                </td>
                <td>
                    ${item.goods.name}
                </td>
                <td>
                    <span class="price">￥${item.price}</span>
                </td>
                <td>
                    <span class="opr" onclick="toChange(-1,${item.id})">-</span>
                     <input type='' value="${item.nums}" class="inpunum" id="input${item.id}"/>
                    <span class="opr" onclick="toChange(1,${item.id})">+</span>
                </td>
                <td>
                    <span class="totalprice" id="cc${item.id}">￥${(item.price*item.nums).toFixed(1)}</span>
                </td>
                <td>
                    <a href="#" onclick="todel(${item.id})">删除</a>
                </td>
            </tr>
        `
        tablebody+=tableBodyTr;
    }

    let tableEnd=`</table>`;
    let totalpriceArea=`<div id='totalprice' class='tpr'></div>`;
    let tableInfo=tableStart+tableHeader+tablebody+tableEnd+totalpriceArea;
    document.querySelector("#shopcartarea").innerHTML=tableInfo;
}
//全选功能
function checkAll(){
    let flag=document.querySelector("#selectAll").checked;
    let carts=$(".checkbox");
    if(flag){
        carts.prop("checked",true);
        document.querySelector("#selectAll").nextElementSibling.innerHTML="反选";
        document.querySelector("#selectAll").checked=true;
    }else{
        carts.prop("checked",false);
        document.querySelector("#selectAll").nextElementSibling.innerHTML="全选";
        document.querySelector("#selectAll").checked=false;
    }
    totalPrice();
}

function totalPrice() {
    let count=0;
    let total=0;
    let carts=$(".checkbox");
    for(let i=0;i<carts.length;i++){
        let cart=$(carts[i]);
        if(cart.prop("checked")){
            count+=1;
            total+=shopcartListData[i].nums*shopcartListData[i].price;
        }
    }
    total=total.toFixed(2);
    $("#selectedcount").text(count);
    $("#total").text("￥"+total);
}
/*
    获取总价格
*/
function getTotalPrice(){
    document.querySelector('#totalprice').innerHTML=`
        <span>已选择</span><span id='selectedcount' class='nub' >0</span><span>件商品</span>
        总价:<span class='pr' id="total">￥0.00</span>
        <button class='btn' onclick="settle()">去结算</button>
    `;
}
//选中商品信息
function selectGood(id){
    let checkbox=$("#"+id);
    totalPrice();
    if(!checkbox.prop("checked")){
        //有一个没有被选
        document.querySelector("#selectAll").nextElementSibling.innerHTML="全选";
        document.querySelector("#selectAll").checked=false;
    }else{
        let carts=$(".checkbox");
        for(let i=0;i<carts.length;i++){
            let cart=$(carts[i]);
            if(!cart.prop("checked")){
                return;
            }
        }
        document.querySelector("#selectAll").nextElementSibling.innerHTML="反选";
        document.querySelector("#selectAll").checked=true;
    }
    totalPrice();
}

function toChange(nums,id) {
    if(nums==-1){
        console.log("减操作");
        let num=parseInt($("#input"+id).val());
        num+=nums;
        $("#input"+id).val(num);
        console.log(num);
        if(num==1){
            alert("至少为一件");
            return;
        }
    }else{
        console.log("加操作");
        let num=parseInt($("#input"+id).val());
        num+=nums;
        $("#input"+id).val(num);
    }
    $.ajax({
        url:"cart/update",
        type:"get",
        dataType:"json",
        data:{
            "id":id,
            "nums":nums,
        },
        success:function (res) {
            if(res.code==200){
                for(let i=0;i<shopcartListData.length;i++){
                    if(shopcartListData[i].id==id){
                        let nums=parseInt($("#input"+id).val());
                        console.log(nums);
                        console.log(shopcartListData[i].price);
                        let price=(nums*shopcartListData[i].price).toFixed(1);
                        $("#cc"+id).text("￥"+price);
                        break;
                    }
                }
                query();
            }
        }
    })
}

function todel(id) {
    $.ajax({
        url:"cart/todel",
        type:"get",
        datatype:"json",
        data:{
            "id":id,
            "userid":sessionStorage.getItem("userid"),
        },
        success:function (res) {
            if(res.code==200){
                alert(res.message);
                let count=0;
                for(let item of res.data)
                    count+=1;
                document.getElementById("shopNum").innerHTML=count;
                document.getElementById("shopNum").style.color="blue";
                renderCartList(res.data);
                getTotalPrice();
            }
        }
    })
}

function settle() {
    let ids=[];
    let carts=$(".checkbox");
    for(let i=0;i<carts.length;i++)
    {
        let cart=$(carts[i]);
        if(cart.prop("checked")){
            ids.push(shopcartListData[i].id);
        }
    }
    if(ids.length==0){
        alert("请选择购买的商品")
        return;
    }
    window.location.href="settle.html?ids="+ids.join(",");
}
